package com.my.springcloud.ribbon;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class RuleServiceImpl implements RuleService {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private final int getAndIncrement(){
        int current,next;
        do {
            current = atomicInteger.get();
            next = current >= 2147483647 ? 0 : current+1;
        } while (!atomicInteger.compareAndSet(current,next));
        log.info("第{}次请求该链接",next);
        return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstanceList) {
        if(serviceInstanceList==null || serviceInstanceList.isEmpty()){
            return null;
        }else{
            int index = getAndIncrement()%serviceInstanceList.size();
            return serviceInstanceList.get(index);
        }
    }
}
